#!/usr/bin/python3


from moviepy.editor import VideoFileClip
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton , QFileDialog,QMessageBox
from PyQt5.QtCore import QSize
from Ui_gif_tool import Ui_MainWindow
import os

class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pushButton_load.clicked.connect(self.display_path)
        self.pushButton_trans.clicked.connect(self.trans_to_gif)
        self.pushButton_fpsSet.clicked.connect(self.fps_set)

        self.fps = 1

    def display_path(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择文件")
        if file_path:
            self.lineEdit_filePath.setText(file_path)
    
    def fps_set(self):
        
        try:
            self.fps = int(self.lineEdit_fpsSet.text())
            if not 0 <= self.fps <= 100:
                raise ValueError("FPS值应在0到100之间")
        except ValueError as e:
            QMessageBox.critical(self, "输入错误", str(e))
        else:
            QMessageBox.information(self, "设置成功", "FPS设置成功")
    
    def trans_to_gif(self):
        
        try:
            # # 指定AVI视频文件的路径
            video_file = self.lineEdit_filePath.text()

            # 创建VideoFileClip对象
            clip = VideoFileClip(video_file)

            # 将视频转换为GIF
            clip.write_gif("output_gif.gif", fps = self.fps)  # fps参数表示每帧之间的时间间隔（以秒为单位）

            # 关闭视频
            clip.close()

            self.label_transStaus.setText('转换完成')

        except Exception as e:
            QMessageBox.critical(self, "转换失败", f"转换过程中出现错误：{e}")

        finally:
            QMessageBox.information(self, "设置成功", "转换成功")

def main():
    app = QApplication([])
    win = MainWindow()
    win.resize(QSize(600, 250))
    win.show()
    app.exec_()

if __name__ == '__main__':
    main()

